var less	= require('less');
var fs 		= require('fs');
var Step = require('./../../libs/step');

exports.init = function(request, response){
	var _req = url2json(request.url),
		lessFile = _req.lessFile,
		ns = _req.ns; // 读取 url 的命名空间
	
	if (!lessFile){		
		show500(response, '未发行对应的样式文件！');
		return;
	}
	
	// 指定包空间
	var ns_arr = [
	    'C:/project/bigfoot/style'
    ];
	ns && ns_arr.push(ns);

	Step(function(){
		
		console.log('请求 LESS 命名空间：' + lessFile.split('/').pop());
		fs.readFile(lessFile, "utf8", this);
		
	}, function(err, lessFile){
		// 背景图的路径按 CSS 为基准。但因为 CSS 处于 Node 服务器上，所以要指定到 Tomcat 上才行。
		var assetFilePath = '@assetFilePath: "http://localhost:8080/sport/asset/images";\n';
		var assetFilePath = '@assetFilePath: "{0}";\n'.format(_req.picPath);
		
		if(err){
			show500(response, '未发行对应的样式文件！原因：' + err.toString());
			return;
		};
		
		var parser = new(less.Parser)({
			paths : ns_arr
		});
		parser.parse(assetFilePath + lessFile, this);
		
	}, function(err, tree){
		if (err) { 
			show500(response, 'LESS 解析 less 失败，原因：' + err.message);
			return console.error(err);
		}
		
		//console.log('parse:' + lessFile);
		response.writeHead(200, {'Content-Type': 'text/css; charset=UTF-8'});
		
		var isDebug = _req.isdebug; // 是否压缩样式
		
		try{
			if(!isDebug || isDebug == 'false') 
				response.end(tree.toCSS({ compress: true }));
			else if(isDebug == 'true')
				response.end(tree.toCSS({ compress: false }));
			
			var deployUsed = tree.toCSS({ compress: true });
			// 总是 localhost/app 后面有一个 app 项目名
			deployUsed = deployUsed.replace(/http:\/\/localhost:8080\/\w+/i, _req.MainDomain);
			
			// 保存文件
			// 父级 css 目录下，save to file
			toCSS(lessFile.replace(/(.*?\/)(\w+)\.less/, '$1../Style/$2.css'), deployUsed);
		}catch(e){
			var msg = 'LESS 解析 less 失败，请检查 LESS 文件是否写错！原因:' + e;
			console.error(msg);
			response.end(msg);
			return;		
		}
	});
}

// fs 覆盖文件
function toCSS(newlessFile, css){
	var _fd;
	Step(function() {
		fs.open(newlessFile, 'w', this);
	}, function(err, fd) {
		if (err) throw err;
		
		_fd = fd;
		var wBuff = new Buffer(css),
			buffPos = 0,
			buffLen = wBuff.length,
			filePos = 0;

		fs.write(fd, wBuff, buffPos, buffLen, filePos, this);
	}, function(err, wbytes, data) {
		if (err) throw err;
		console.log('保存 CSS 压缩文件成功！wrote ' + wbytes + ' bytes，保存路径：' + newlessFile);
		fs.close(_fd);
	});
}

function show500(res, msg){
	if(res){
		msg = msg || '读取 LESS 文件异常，原因未知！';
		res.writeHead(500, {'Content-Type': 'text/html;charset=UTF-8'});
		res.end(msg);
		console.log('------------------------------------------');	
		console.log('[Statics]' + new Date + msg);
	}else{
		console.log('Request 对象不存在！');
	}
}

/**
 * 
 * @param  {String} ids [description]
 * @return {Object}     [description]
 */
function url2json(ids){
	var _json = {};
	if(ids && ids.indexOf("?") != -1){
		
		ids = ids.split('?');
		ids = ids.pop();
		ids = ids.replace(/&/g, '","').replace(/=/g, '":"');
		if(ids){
			_json = JSON.parse('{"' + ids +'"}');
		} 
		// var ids = ids.split('&');
		// var json = {};
		// for(var arr, i = 0, j = ids.length; i < j; i++){
		// 	arr = ids[i];
		// 	arr = arr.split('=');
		// 	json[arr[0]] = arr[1];
		// }
	}
	return _json;
}
